<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header" @click="backChange">
        <el-icon size="20"><ArrowLeft /></el-icon>
        <span> 编辑Banner</span>
      </div>
    </template>

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="Banner名称" prop="name" width="400">
        <el-input v-model="ruleForm.name" placeholder="请输入Banner名称" />
      </el-form-item>

      <el-form-item label="电脑端封面" v-if="type == 1" prop="picUrl">
        <ImageUpload
          :limit="1"
          :modelValue="modelValueList"
          @update:modelValue="modelValue"
        ></ImageUpload>
      </el-form-item>

      <el-form-item label="移动端封面" prop="picUrl" v-if="type == 2">
        <ImageUpload
          :limit="1"
          :modelValue="modelValueList"
          @update:modelValue="modelValue"
        ></ImageUpload>
      </el-form-item>

      <el-form-item label="电脑端链接" prop="url" v-if="type == 1">
        <el-input v-model="ruleForm.url" placeholder="请输入电脑端链接" />
        <el-icon
          @click="maskBtn"
          :size="20"
          style="cursor: pointer; margin-left: 5px"
        >
          <Link />
        </el-icon>
      </el-form-item>

      <el-form-item v-if="type == 1">
        <a href="" style="color: #0f5cfb; font-size: 16px; font-weight: 500"
          >前往官网</a
        >
      </el-form-item>

      <el-form-item label="移动端链接" prop="url" v-if="type == 2">
        <el-input v-model="ruleForm.url" placeholder="请输入移动端端链接 " />
        <el-icon
          @click="maskBtn"
          :size="20"
          style="cursor: pointer; margin-left: 5px"
        >
          <Link />
        </el-icon>
      </el-form-item>

      <el-form-item v-if="type == 2">
        <a href="" style="color: #0f5cfb; font-size: 16px; font-weight: 500"
          >扫码止移动端</a
        >
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >提交</el-button
        >
        <!-- <el-button @click="resetForm(ruleFormRef)">预览</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 弹出框 -->

    <el-dialog v-model="dialogFormVisible" title="常用链接">
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="常用功能"
          name="first"
          style="border-bottom: 1px solid #ccc"
        >
          <el-radio-group v-model="radio">
            <el-row>
              <el-col class="calssName" :span="24">
                <el-radio :value="0">智能填报</el-radio></el-col
              >
              <el-col class="calssName" :span="24">
                <el-radio :value="1">一键填报</el-radio></el-col
              >
              <el-col class="calssName" :span="24">
                <el-radio :value="2">专业定位测评</el-radio></el-col
              >
              <el-col class="calssName" :span="24">
                <el-radio :value="5">智能选科</el-radio></el-col
              >
            </el-row>
          </el-radio-group>
        </el-tab-pane>
        <el-tab-pane
          label="商品服务"
          name="second"
          style="border-bottom: 1px solid #ccc"
        >
          <el-row style="width: 100%">
            <el-col class="calssName" :span="24">
              <el-radio-group v-model="goodsRadio" class="ml-4">
                <el-radio
                  v-for="item in tableData"
                  :key="item.id"
                  :value="item.id"
                  size="large"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="getAdd">添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览dialog -->
    <!-- <el-dialog v-model="dialogFormVisible2" title="效果预览">
      <div class="box">
        <div class="padding">
          <el-row>
            <el-col :span="18" class="boxOne">
              <p>电脑端效果</p>
              <div class="boxPic">
                <img v-if="type == 1" :src="ruleForm.pic" />
                <p v-else>电脑端暂未效果</p>
              </div>
            </el-col>
            <el-col :span="6" class="boxTow">
              <p>移动端效果</p>
              <div class="middle">
                <img
                  style="width: 100%; height: 320px; margin-top: 5px"
                  v-if="type == 2"
                  :src="ruleForm.pic"
                />
                <div v-else class="boxPic2">移动端暂无效果</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible2 = false"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog> -->
  </el-card>
</template>
<script setup>
import { bannerAdd } from '@/api/banner/index';
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
// import useSettingsStore from '@/store/modules/settings';
import { allServicesList } from '@/api/service/service.js';
// const settingsStore = useSettingsStore();
// const { vipserviceid, vipshengxuserviceid } = settingsStore?.platformInfo;
// banner模块接口和数据
import banner from '@/modules';
const { bannerInfoApi } = banner;
const router = useRouter();
const route = useRoute();
const tableLoading = ref(false);
const type = ref('');
const tableData = ref([]);
const radio = ref('');
const goodsRadio = ref('');
const pageDate = ref({
  page: 1,
  pageSize: 20,
});
const PC_URL = {
  0: '/batchInfo',
  1: '/batchInfo',
  2: '/appraisal',
  5: '/optional',
};
const dialogFormVisible = ref(false);
//预览
// const dialogFormVisible2 = ref(false);

const activeName = ref('first');

const row = ref([]);
const detaliList = ref([]);
const category = ref('');

const ruleFormRef = ref(null);

const modelValueList = ref([]);

let ruleForm = ref({
  name: '',
  pic: '',
  url: '',
  picUrl: '',
});

const modelValue = (val) => {
  ruleForm.value.picUrl = val; // 保存单张图片
};

const getAdd = () => {
  console.log(goodsRadio.value, activeName.value);
  if (activeName.value == 'first') {
    ruleForm.value.url = PC_URL[radio.value] ?? ruleForm.value.url;
  } else {
    ruleForm.value.url = goodsRadio.value
      ? `/shopserve/shopDet?id=${goodsRadio.value}`
      : ruleForm.value.url;
  }
  dialogFormVisible.value = false;
};
const backChange = () => {
  router.push({ path: 'advertisement' });
};
const rules = reactive({
  name: [{ required: true, message: '请输入Banner名称', trigger: 'blur' }],
  picUrl: [{ required: true, message: '请上传封面', trigger: 'blur' }],
});

function maskBtn() {
  radio.value = getKeyByValue(PC_URL, ruleForm.value.url);
  dialogFormVisible.value = !dialogFormVisible.value;
}
/**
 * 根据 value 查找对应的 key
 * @param {Object} obj - 映射对象
 * @param {string} value - 要查找的值
 * @returns {string|null} - 找到则返回 key，否则返回 null
 */
function getKeyByValue(obj, value) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] === value) {
      return Number(key);
    }
  }
  return value;
}

let editFn = (params) => {
  bannerAdd(params).then((res) => {
    ElMessage({
      message: res.msg,
      type: 'success',
    });

    router.push({ path: 'advertisement', query: { category: category.value } });
  });
};
// 创建接口
const submitForm = (formEl) => {
  let params = ref({
    id: row.value.id,
    storeId: JSON.parse(localStorage.getItem('userDateInfo'))?.storeId,
    name: ruleForm.value.name,
    type: row.value.type,
    status: detaliList.value.status,
  });
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (detaliList.value.type == 1) {
        params.value.pc_img_url = ruleForm.value.picUrl;
        params.value.pc_url = ruleForm.value.url;
        params.value.m_img_url = '';
        params.value.m_url = '';
        editFn(params.value);
      } else if (detaliList.value.type == 2) {
        params.value.pc_img_url = '';
        params.value.pc_url = '';
        params.value.m_img_url = ruleForm.value.picUrl;
        params.value.m_url = ruleForm.value.url;
        editFn(params.value);
      }
    } else {
    }
  });
};

//预览
// const resetForm = () => {
//   dialogFormVisible2.value = true;
// };

const detailInfo = (id) => {
  bannerInfoApi({ id: id }).then((res) => {
    const { data } = res;
    detaliList.value = data;
    ruleForm.value.name = data.name;
    ruleForm.value.url = data.url;
    ruleForm.value.picUrl = data.img_url;
    modelValueList.value = [ruleForm.value.picUrl];
  });
};
const handleClick = (index) => {
  if (index.props.label == '商品服务') {
    const queryString = ruleForm.value.url.split('?')[1]; // "id=64"
    let id = null;
    if (queryString) {
      const params = queryString.split('&');
      params.forEach((param) => {
        const [key, value] = param.split('=');
        if (key === 'id') {
          id = value;
        }
      });
    }
    goodsRadio.value = Number(id);
  }
};

function servicesListChange() {
  tableLoading.value = true;
  allServicesList(pageDate.value)
    .then((res) => {
      if (res.code === 20000) {
        tableData.value = res.data.data;
        tableLoading.value = false;
      } else {
        tableLoading.value = false;
      }
    })
    .catch(() => {
      tableLoading.value = false;
    });
}

onMounted(() => {
  type.value = route.query.type;
  row.value = route.query;
  detailInfo(route.query.id);
  category.value = route.query.category;
  servicesListChange();
});
</script>
<style lang="scss" scoped>
:deep(.el-dialog__body) {
  border-top: 1px solid #ccc !important;
  border-bottom: 1px solid #ccc !important;
}
:deep(.el-input) {
  width: 400px !important;
  height: 40px !important;
}
:deep(.el-row) {
  width: 100% !important;
}

.box-card {
  margin: 20px;
  .box {
    width: 100%;
    background: #f7f8fa;
    border-radius: 4px;
    padding: 10px 18px 38px;
    height: 370px;
    box-sizing: border-box;
    color: #86909c;
    .boxOne {
      .boxPic {
        width: 95%;
        height: 320px;
        margin-top: 5px;
        border: 1px solid #ccc;
        margin-top: 5px;
        img {
          width: 100%;
          height: 320px;
          object-fit: cover;
          display: block;
        }
        p {
          display: flex;
          justify-content: center;
          align-items: center;
          line-height: 320px;
        }
      }
    }
    .boxTow {
      .boxPic2 {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 320px;
        border: 1px solid #ccc;
        margin-top: 5px;
        .middle {
          margin-top: 5px;
        }
      }
    }
  }
  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .calssName {
    margin-bottom: 20px;
    margin-left: 10px;

    .box {
      display: flex;
      align-items: center;
      height: 94px;
      padding-bottom: 20px;
    }
    .txt {
      display: inline-block;
      position: relative;
      top: -40px;
      left: 5px;
    }
  }
}
.demo-tabs {
  margin-top: 20px;
}
</style>
